package cn.tedu.weibo.controller;

import cn.tedu.weibo.response.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/v1")
public class UploadController {
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        //得到原始文件名  a.jpg
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        //得到文件的后缀    .jpg
        String suffix = fileName.substring(fileName.lastIndexOf('.'));
        //得到唯一文件名  UUID.randomUUID()得到一个唯一标识符(字符串)
        fileName = UUID.randomUUID()+suffix;
        System.out.println(fileName);//db7cdeb9-1a0c-404f-a33c-91d45b18e4f4.jpg
        //文件夹路径  d:/files/2024/03/13/
        String dirPath = "d:/files";
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        File dirFile = new File(dirPath+datePath);
        //如果不存在则创建
        if (!dirFile.exists()){
            dirFile.mkdirs();//创建文件夹
        }
        String filePath = dirPath+datePath+fileName;
        //把文件保存到指定的路径  异常抛出
        file.transferTo(new File(filePath));
        //     /2023/01/12/xxxx.jpg
        return JsonResult.ok(datePath+fileName);
    }

    @PostMapping("remove")
    public JsonResult remove(String imgUrl){
        System.out.println("imgUrl = " + imgUrl);
        new File("d:/files"+imgUrl).delete();
        return JsonResult.ok();
    }
}
